package edu.ajou.scw;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Logout
 */
@WebServlet("/Logout")
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logout() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		
		
		DatabaseConnector conn = new DatabaseConnector();
		
		String sql = String.format("update `login_info` set `logon`=\"0\" where `id` = \"%s\"", id);
		
		if (conn.query(sql) > 0)
			Log.d(id + " is logged out.");
		
		String team_id = conn.findTeamByLeader(id);
		Team team = conn.getTeamById(team_id);
		
		if (team_id != null)
		{
			String delete = String.format("delete from `team_info` where `leader` = \"" + id + "\"", id);
			if (conn.query(delete) > 0)
			{
				String root = "/var/lib/tomcat7/webapps/PresentationServer/" + team_id + "/";
				Log.d(id, team_id, "Team [" + team_id + "] is closed because team leader " + id + " is gone.");
				File dir = new File(root);
				if (dir.exists() && dir.isDirectory())
				{
					String[] files = dir.list();
					for (int i=0; i<files.length; i++)
					{
						File f = new File(root + files[i]);
						f.delete();
					}
					dir.delete();
				}
				
				team.closeTeam();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}
